<template>
  <!--  @ok="handleSubmit"-->
  <div>
    <BasicModal v-bind="$attrs" @register="register" showFooter :title="getTitle" width="70%" :showOkBtn="false"
      :showCancelBtn="false">
      <Form :model="formData" label-align="right" ref="formRef">
        <div v-for="(item, index) in formSchemaList">
          <FormItem v-bind="item" :name="item.field">
            <Select v-if="item.component === 'Select'" :placeholder="'请选择' + item.label"
              v-model:value="formData[item.field]" v-bind="item.componentProps"></Select>
            <Upload v-if="item.component === 'Upload'" v-bind="item.componentProps" accept=""
              :before-upload="beforeUpload" :multiple="false" :show-upload-list="false"
              class="upload-modal-toolbar__btn">
              <a-button type="primary" :loading="loading">
                {{ t('component.upload.choose') }}
              </a-button>
            </Upload>
            <Image :src="formData[item.field]" :width="150" v-if="item.component === 'Image'"></Image>
            <div v-if="item.component === 'div'">
              <div>{{ formData.size }}{{
                formData.unit }}</div>
              <div>{{ formData.thumbUrl }}</div>
            </div>
          </FormItem>
        </div>
        <!-- <Image :width="200" :src="formData.thumbUrl" v-if="formData.thumbUrl"></Image> -->
      </Form>


    </BasicModal>


  </div>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { BasicModal, useModalInner } from '@/components/Modal';
import SelectStorageList from "@/views/store/components/SelectStorageList/index.vue"
import { BasicTree, TreeItem } from '@/components/Tree';
import { uploadByRateApi } from '@/api/sys/upload';
import { Modal, Upload } from 'ant-design-vue';
import { useI18n } from '@/hooks/web/useI18n';
import { AxiosProgressEvent } from 'axios';
import { get } from 'lodash-es';

import {
  Form,
  FormItem,
  Image,
  Select
} from 'ant-design-vue';
import { useMessage } from '@/hooks/web/useMessage';
import { useRefs } from '@vben/hooks';
import util from "@/utils/util";
import { buildUUID } from '@/utils/uuid';
import { checkImgType, getBase64WithFile } from '../helper';
import { log } from 'vxe-pc-ui';

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const treeData = ref<TreeItem[]>([]);
const { t } = useI18n();

const { createMessage } = useMessage();

const formSchemaList = [
  {
    label: '压缩比例',
    field: 'rate',
    component: 'Select',
    required: true,
    componentProps: {
      options: [
        { label: '60%', value: 0.6 },
        { label: '50%', value: 0.5 },
        { label: '40%', value: 0.4 },
        { label: '30%', value: 0.3 },
        { label: '20%', value: 0.2 },

      ],
    },
  },
  {
    field: 'imgArr',
    label: '图片',
    required: false,
    component: 'Upload',
    componentProps: {
      multiple: false,
      accept: ['.png', '.jpeg', '.jpg'],
      maxSize: 10,
      maxNumber: 1,
    },
  },
  {
    field: 'thumbUrl',
    label: '最后生成的图片',
    required: false,
    component: 'Image',

  },
  {
    field: 'size',
    label: '文件大小',
    required: false,
    component: 'div',

  },

]
const formData = ref({
});
const labelCol = ref({ span: 10 });
const wrapperCol = ref({ span: 13 });
const formRef = ref();

const loading = ref(false);

const selectStorage = ref();



const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //打开弹层后的回调
  setModalProps({ confirmLoading: false });

  isUpdate.value = data?.isUpdate;
  formData.value = {};

});

const getTitle = computed(() => "压缩测试");

const visible = ref(false);



function closeFn() {
  closeModal()
  emit("success");

}




function handleOk() {
  visible.value = false;
}

const fileListRef = ref([]);
// 上传前校验
function beforeUpload(file: File) {
  const { size, name } = file;
  const maxSize = 10;
  // 设置最大值，则判断
  if (maxSize && file.size / 1024 / 1024 >= maxSize) {
    createMessage.error(t('component.upload.maxSizeMultiple', [maxSize]));
    return false;
  }

  const commonItem = {
    uuid: buildUUID(),
    file,
    size,
    name,
    percent: 0,
    type: name.split('.').pop(),
  };
  // 生成图片缩略图
  if (checkImgType(file)) {
    // beforeUpload，如果异步会调用自带上传方法
    // file.thumbUrl = await getBase64(file);
    getBase64WithFile(file).then(({ result: thumbUrl }) => {
      fileListRef.value = [
        ...unref(fileListRef),
        {
          thumbUrl,
          ...commonItem,
        },
      ];
    });
  } else {
    fileListRef.value = [...unref(fileListRef), commonItem];
  }
  // console.log("---commonItem:", commonItem);

  loading.value = true;
  uploadByRateApi(
    {
      data: { rate: formData.value.rate },
      file: commonItem.file,
      name: "file",
      filename: commonItem.filename,
    },
    function onUploadProgress(progressEvent: AxiosProgressEvent) {
      const complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
      // item.percent = complete;
    },
  ).then(res => {
    // console.log("---res:", res.data);
    // getBase64WithFile(res.data)
    let json = res.data.data;
    console.log("---json:", json);

    loading.value = false;
    let thumbUrl = json.url;
    formData.value.thumbUrl = thumbUrl;
    formData.value.size = json.size;
    formData.value.unit = json.unit;

    // });
    // formData.value.thumbUrl = res.data
    window.open(thumbUrl)
    // get(res, "data")

  });
  return false;
}

</script>

<style lang="less">
.m_w_100 {
  width: 90%;

  .ant-col-6 {
    flex: 0 0 10%;
    max-width: 10%;
  }
}

.ant-form {
  .ant-form-item {
    margin-bottom: 10px;
  }
}
</style>
